package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"log"
)

var ctx = context.Background()
var rdb *redis.Client

func initializeRedisClient() (err error) {
	rdb = redis.NewClient(&redis.Options{
		//ip:port
		Addr: "localhost:6379",
		//密码, 无密码设置为 "" 空串
		Password: "",
		//使用第几个数据库 SELECT 0
		DB: 0,
		//连接池大小
		PoolSize: 100,
	})

	_, err = rdb.Ping(ctx).Result()
	return
}

func main() {
	if err := initializeRedisClient(); err != nil {
		log.Printf("connect 2 redis failed err : %v\n", err)
		panic(err)
	}
	fmt.Println("connected")

	//设置值
	err := rdb.Set(ctx, "key1", "value1", 0).Err()
	if err != nil {
		panic(err)
	}

	//查询
	res, err := rdb.Get(ctx, "key1").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("res, key1=", res)

	res2, err := rdb.Get(ctx, "key2").Result()
	if err == redis.Nil {
		fmt.Println("key2 does not exist")
	} else if err != nil {
		panic(err)
	} else {
		fmt.Println("res2, key2=", res2)
	}

	hGetAllTest()

}

func hGetAllTest() {
	rdb.HSet(ctx, "user", "name", "gin")
	rdb.HSet(ctx, "user", "age", 32)
	v := rdb.HGetAll(ctx, "user").Val()
	fmt.Println(v)

	v2 := rdb.HMGet(ctx, "user", "name", "age").Val()
	fmt.Println(v2)

	v3 := rdb.HMGet(ctx, "user", "age").Val()
	fmt.Println(v3)
}
